package com.trainfinder.proxy;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Proxy extends AbstractProxy {

	private Runnable portEightly;

	private ServiceProviderFactory serviceProviderFactory;

	private ThreadCreatedListener threadCreatedListener;

	public Proxy(ServiceProviderFactory serviceProviderFactory) {
		this.serviceProviderFactory = serviceProviderFactory;
	}

	public void addThreadCreatedListener(
			ThreadCreatedListener threadCreatedListener) {
		this.threadCreatedListener = threadCreatedListener;
	}

	int i = 0;

	protected Service getService() throws ServerCreationException {
		final ServiceProvider serviceProvider = serviceProviderFactory
				.newInstance();

		ConstructListeningThread(serviceProvider);

		return new AbstractService() {

			public InputStream getInputStream() throws ServerCreationException {
				try {
					return serviceProvider.getLocalService().getInputStream();
				} catch (IOException e) {
					throw new ServerCreationException(e);
				} catch (ServerCreationException e) {
					throw new ServerCreationException(e);
				}
			}

			public OutputStream getOutputStream()
					throws ServerCreationException {
				try {
					return serviceProvider.getRemoteService().getOutputStream();
				} catch (IOException e) {
					throw new ServerCreationException(e);
				} catch (ServerCreationException e) {
					throw new ServerCreationException(e);
				}
			}

			 

		};
	}

	private void ConstructListeningThread(final ServiceProvider serviceProvider) {
		// portEightly = new RemoteRunnable(serviceProvider,
		// new SimpleLoggerImpl(), ++i);

		portEightly = new RemoteRunnable(serviceProvider, new NullLoggerImpl(),
				++i);

		Thread t = new Thread(portEightly);
		t.start();

		if (threadCreatedListener != null) {
			threadCreatedListener.onThreadCreated(t);
		}

	}

	public static void main(String[] a) {
		try {
			new Proxy(new ProxyServiceFactory()).start();
		} catch (ServerCreationException e) {
			// TODO Auto-generated catch block
			// / e.printStackTrace();
		}
	}

	public void close() {
		serviceProviderFactory.close();

	}

}
